﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using PrerequisitesService.Exceptions;

namespace PrerequisitesService.Services {

    /// <summary>
    /// 
    /// </summary>
    public class PrerequisitesService {
        private const string EVENT_LOG_MESSAGES_DLL = "EventLogMessages.dll";
        private const string EVENT_MESSAGE_FILE = "EventMessageFile";
        private const string HKEY_EVENT_LOG_PATH = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\Rerun";

        /// <summary>
        /// 
        /// </summary>
        /// <exception cref="PrerequisitesException"></exception>
        public PrerequisitesService() {
            try {
                CheckForEventMessageFileRegistryEntry();
            } catch(Exception e) {
                throw new PrerequisitesException(string.Format("There was a problem trying to check for prerequisites: {0}", e.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <exception cref="PrerequisitesException"></exception>
        private void CheckForEventMessageFileRegistryEntry() {
            try {
                string eventMessageFileValue = (string)Registry.GetValue(string.Format(@"{0}\{1}", HKEY_EVENT_LOG_PATH, EVENT_MESSAGE_FILE), string.Empty, string.Empty);

                if(string.IsNullOrEmpty(eventMessageFileValue)) {
                    Registry.SetValue(HKEY_EVENT_LOG_PATH, EVENT_MESSAGE_FILE, Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), EVENT_LOG_MESSAGES_DLL));
                }
            } catch(Exception e) {
                throw new PrerequisitesException(string.Format("There was a problem checking for the EventMessageFile registry entry: {0}", e.Message));
            }
        }
    }
}